const dayjs = require("dayjs");
const funTool = require("../tool/funTool");

let formatText = {
  request: function (req) {
    let logText = new String();
    let method = req.method;
    //访问方法
    logText += "request method: " + method + "\n";
    //请求原始地址
    logText += "request originalUrl:  " + req.originalUrl + "\n";
    //客户端ip
    logText += "request client ip:  " + req.ip + "\n";

    //请求参数
    if (method === "GET") {
      logText += "request query:  " + JSON.stringify(req.query) + "\n";
      // startTime = req.query.requestStartTime;
    } else {
      logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
      // startTime = req.body.requestStartTime;
    }

    return logText;
  },

  handle: (info) => {
    let logText = new String();
    //响应日志开始
    logText += "\n" + `***************info log start ***************日志记录时间： ${dayjs().format("YYYY.MM.DD HH:mm:ss")}` + "\n";
    //响应内容
    logText += "\n" + info + "\n";
    //响应日志结束
    logText += "*************** info log end ***************************************************************************" + "\n";
    return logText;
  },
  error: (ctx, err) => {
    let logText = new String();
    //错误信息开始
    logText += "\n" + `*************** error log start ***************日志记录时间： ${dayjs().format("YYYY.MM.DD HH:mm:ss")}` + "\n";
    //添加请求日志
    logText += formatText.request(ctx.request);
    //错误名称
    logText += "err name: " + err.name + "\n";
    //错误信息
    logText += "err message: " + err.message + "\n";
    //错误详情
    logText += "err stack: " + err.stack + "\n";
    //错误信息结束
    logText += "*************** error log end ***************************************************************************" + "\n";
    return logText;
  },
};

module.exports = {
  //封装操作日志
  log(msg, data) {
    let msgTotal = msg;

    if (data) {
      if (typeof data === "object") {
        msgTotal += ":" + JSON.stringify(data);
      } else {
        msgTotal += ":" + data;
      }
    }

    let msgStr = formatText.handle(msgTotal);
    funTool.writeLog(msgStr);
  },

  errError(msg) {
    let msgStr = formatText.handle(msg);
    funTool.writeLog(msgStr, "error");
  },
  //封装错误日志
  ctxError(error, ctx) {
    if (ctx && error) {
      let msg = formatText.error(ctx, error);
      funTool.writeLog(msg, "error");
    }
  },
};
